package com.xigua.xcar.nearby;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.MKDrivingRouteResult;
import com.xigua.xcar.BMapApiDemoApp;
import com.xigua.xcar.LocationUpdateListener;
import com.xigua.xcar.R;
import com.xigua.xcar.RoutePlan;
import com.xigua.xcar.base.BaseActivity;
import com.xigua.xcar.constant.Constants;
import com.xigua.xcar.shoplist.ShopListActivity;
import com.xigua.xcar.util.CommonListUtil;

public class NearbyActivity extends BaseActivity {
	private static final String tag = "NearbyActivity";

//	private MKSearch mSearch = new MKSearch();
//	private MKAddrInfo mAddrInfo = null;
//	private boolean mIsDevelop = true;
//	LocationListener mLocationListener = null;//create时注册此listener，Destroy时需要Remove
	private EditText mEdtInput = null;
	private TextView mTxtPos = null;
	private LocationUpdateListener mListener = null;
	private OnClickListener mGoListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Log.i(tag, "onClick");
			jumpToShopListActivity(1,1);
		}
	};
	private OnClickListener mClearListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			mEdtInput.setText("");
		}
	};
	private OnClickListener mAddListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			jumpToShopListActivity(3,1);
		}
	};
	private OnClickListener mWashListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			jumpToShopListActivity(2,1);
		}
	};

	@Override
	protected void finalize() throws Throwable {
		// 注销的注意事项
		super.finalize();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.i(tag, "onCreate");
		super.onCreate(savedInstanceState);
		BMapApiDemoApp app = (BMapApiDemoApp)getApplication();
//		mIsDevelop = app.mIsDevelopMode;
		setView(R.layout.nearby);
		setTopBarTitle(" 附近-杭州");
		setTitleBar(0, "", 0, "");
		Button goBtn = (Button) this.findViewById(R.id.btn_nearby_go);
		goBtn.setOnClickListener(mGoListener);
		Button mBtnFind = (Button) this.findViewById(R.id.btn_nearby_find);
		mBtnFind.setOnClickListener(mGoListener);
		Button mBtnClear = (Button) this.findViewById(R.id.btn_nearby_clear);
		mBtnClear.setOnClickListener(mClearListener);
		Button add = (Button) this.findViewById(R.id.btn_nearby_addoil);
		add.setOnClickListener(mAddListener);
		Button wash = (Button) this.findViewById(R.id.btn_nearby_washcar);
		wash.setOnClickListener(mWashListener);
		mEdtInput = (EditText) this.findViewById(R.id.edit_nearby_input);
		mEdtInput.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if (KeyEvent.ACTION_UP == event.getAction()) {
					if (KeyEvent.KEYCODE_ENTER == event.getKeyCode()) {
						jumpToShopListActivity(1,1);
					}
				}
				return false;
			}
		});
		mTxtPos = (TextView)this.findViewById(R.id.txt_nearby_curaddress);
		mListener = new LocationUpdateListener() {
			
			@Override
			public void notifyLocationUpdate(String address) {
				Log.i(tag, "notifyLocationUpdate:" + address);
				if(null != address){
					mTxtPos.setText(address);
				}
			}

			@Override
			public void onGetDrivingRouteResult(MKDrivingRouteResult res,
					int error) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onLocationChanged(Location location) {
				// TODO Auto-generated method stub
				
			}
		};
		app.setLocationUpdateListener(mListener);
	}
	
	private static final String KEY_FLAG = "flag";
	
	private boolean getFlagFromSp(){
		boolean ret = false;
		SharedPreferences sp = this.getPreferences(MODE_WORLD_READABLE);
		ret = sp.getBoolean(KEY_FLAG, false);
		return ret;
	}
	
	private void saveFlagToSp(){
		SharedPreferences sp = this.getPreferences(MODE_WORLD_WRITEABLE);
		Editor edit = sp.edit();
		edit.putBoolean(KEY_FLAG, true);
		edit.commit();
	}
	
	private void jumpToShopListActivity(int type,int flag) {
		Editable txt = mEdtInput.getText();
		String ss = txt.toString();
		if(1 == type){
			if ("".equals(ss)) {
				Toast.makeText(NearbyActivity.this, "您输入的关键词为空", Toast.LENGTH_LONG).show();
				return ;
			}
		}
		if(isGetLocation()){
			CommonListUtil.saveLocationPointToSP(this, (int)(RoutePlan.getLocation().getLongitude()*1e6), (int)(RoutePlan.getLocation().getLatitude()*1e6));
			if(!getFlagFromSp()){
				saveFlagToSp();
				Toast.makeText(this, "迈吉卡目前只支持杭州地区，其他地区敬请期待", 3000).show();
			}
			Intent intent = new Intent(NearbyActivity.this,
					ShopListActivity.class);
			intent.putExtra(Constants.REQUEST_TYPE, type);
			intent.putExtra(Constants.REQUEST_KEYWORD, txt.toString());
			intent.putExtra(Constants.REQUEST_ISNEARBY, type);
			NearbyActivity.this.startActivity(intent);
		}else{
			Toast.makeText(NearbyActivity.this, "正在努力的获得您的当前位置，请稍等...", Toast.LENGTH_LONG).show();
		}
	}

	private boolean isGetLocation(){
		if(null == RoutePlan.getLocation() || (0 == RoutePlan.getLocation().getLatitude() || 0 == RoutePlan.getLocation().getLongitude())){
			return false;
		}else{
			return true;
		}
	}
	
	@Override
	protected void onPause() {
    	Log.i(tag, "onPause");
    	BMapApiDemoApp app = (BMapApiDemoApp)getApplication();
    	app.setLocationUpdateListener(null);
		super.onPause();
	}
    
	@Override
	protected void onResume() {
		Log.i(tag, "onResume");
		BMapApiDemoApp app = (BMapApiDemoApp)getApplication();
		if(null == app.getLocationAddress()){
    		mTxtPos.setText("");
    	}else{
    		mTxtPos.setText(app.getLocationAddress());
    	}
		app.setLocationUpdateListener(mListener);
		super.onResume();
	}

	@Override
	protected void handleTitleBarEvent(int buttonId) {
		switch (buttonId) {
		case Constants.LEFTBUTTONID: {
			break;
		}
		case Constants.RIGHTBUTTONID: {
			break;
		}
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.d(tag, "back");
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { //按下的如果是BACK，同时没有重复
	    	 AlertDialog.Builder builder = new AlertDialog.Builder(this);  
	    	    builder.setTitle("提示");  
	    	    builder.setMessage("确定要退出程序吗?");  
	    	    builder.setPositiveButton("确定",  
	    	            new DialogInterface.OnClickListener() {  
	    	                public void onClick(DialogInterface dialog, int whichButton) {           
	    	                	NearbyActivity.this.finish();  
	    	                }  
	    	            });  
	    	    builder.setNegativeButton("取消",  
	    	            new DialogInterface.OnClickListener() {  
	    	                public void onClick(DialogInterface dialog, int whichButton) {  
	    	                }  
	    	            }).create(); 
	    	
	    	    builder.show();
	    	    
	        return true;
	    }
		return super.onKeyDown(keyCode, event);
	}
}
